package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;
import drds.plus.sql_process.type.impl.IntervalType;

import java.util.Calendar;

/**
 * timestampadd(unit,interval,datetime_expr) Adds the integer expression
 * interval to the date or datetime expression datetime_expr. The unit for
 * interval is given by the unit argument, which should be one of the following
 * columnValueList: MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK,
 * MONTH, QUARTER, or YEAR. The unit value may be specified using one of
 * keywords setAliasAndSetNeedBuild shown, or with a prefix of SQL_TSI_. For example, DAY and
 * SQL_TSI_DAY both are legal.
 *
 * <pre>
 * mysql> SELECT timestampadd(MINUTE,1,'2003-01-02');
 *         -> '2003-01-02 00:01:00'
 * mysql> SELECT timestampadd(WEEK,1,'2003-01-02');
 *         -> '2003-01-09'
 * </pre>
 *
 * @author jianghang 2014-4-16 下午11:11:30
 * @since 5.0.7
 */
public class Timestampadd extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        java.sql.Timestamp timestamp = Type.TimestampType.convert(args[2]);
        Calendar cal = Calendar.getInstance();
        cal.setTime(timestamp);

        IntervalType date = Interval.paseIntervalDate(args[1], args[0]);
        date.process(cal, 1);

        Type type = getReturnType();
        return type.convert(cal.getTime());
    }

    public Type getReturnType() {
        return getType(function.getArgList().get(2));
    }

    public String[] getFunctionNames() {
        return new String[]{"timestampadd"};
    }
}
